package com.sxjh.service;

import com.alibaba.excel.annotation.ExcelProperty;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.sxjh.common.FieldDTO;
import com.sxjh.uitl.PDFUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PdfService {

    /**
     * 获取pdf
     *
     * @param response  res
     * @param list      数据集 不能为空
     * @param fieldSet  需要导出的字段 ，可为空
     * @param fileName  文件名
     * @param mainTitle 主标题
     * @param <T>       T
     */
    public <T> void getPdf(HttpServletResponse response, String fileName, Set<String> fieldSet, List<T> list, String mainTitle) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<FieldDTO> fieldDTOList = new ArrayList<>();
        T t = list.get(0);
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
            FieldDTO fieldDTO = new FieldDTO();
            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation != null && StringUtils.isNoneBlank((annotation.value())[0])) {
                String excelPropertyName = StringUtils.join(annotation.value());
                fieldDTO.setFieldName(field.getName());
                fieldDTO.setFieldValue(excelPropertyName);
            } else {
                fieldDTO.setFieldName(field.getName());
                fieldDTO.setFieldValue(field.getName());
            }
            fieldDTOList.add(fieldDTO);
        }
        exportPDF(response, fileName, list, fieldSet, fieldDTOList, mainTitle);
    }

    private <T> void exportPDF(HttpServletResponse response, String fileName, List<T> list, Set<String> fieldSet, List<FieldDTO> fieldDTOList, String mainTitle) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
            // 构建字节输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 实例化文档对象
            Document document = new Document(PageSize.A4, 10, 10, 10, 10);
            // 创建 PdfWriter 对象 文件的输出路径+文件的实际名称
            // 设置分页
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            // writer.setPageEvent(new PDFMaker());
            document.open();// 打开文档
            // 创建一个段落
            document.add(PDFUtil.getPDFParagraph(mainTitle, 0, 20, Element.ALIGN_CENTER, 1));
            // 标题 {"ID", "姓名", "年龄", "生日", "出生地", "身份证", "住址"};
            List<String> titleList = new ArrayList<>();
            List<Integer> columnWidth = new ArrayList<>();
            if (!CollectionUtils.isEmpty(fieldSet)) {
                for (String field : fieldSet) {
                    Map<String, String> map = fieldDTOList.stream().collect(Collectors.toMap(FieldDTO::getFieldName, FieldDTO::getFieldValue));
                    String title = map.getOrDefault(field, field);
                    titleList.add(title);
                    columnWidth.add(10);

                }
            } else {
                //fieldSet 为空
                for (FieldDTO fieldDTO : fieldDTOList) {
                    if (!"serialVersionUID".equals(fieldDTO.getFieldValue())) {
                        titleList.add(fieldDTO.getFieldValue());
                        columnWidth.add(10);
                    }
                }
            }
            //标题
            String[] titles = titleList.toArray(new String[titleList.size()]);
            // 列宽
            int[] tableWidth = columnWidth.stream().mapToInt(Integer::intValue).toArray();

            //自定义数据列

            // 获取PDFTable
            PdfPTable table = PDFUtil.getPDFTable(tableWidth, titles, list, 0, fieldSet);
            // 添加进文档
            document.add(table);

            // 关闭文档
            if (document != null) {
                document.close();
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            OutputStream os = response.getOutputStream();
            // 设置文件大小
            // response.setContentLength((int) f.length());
            os.write(baos.toByteArray());
        } catch (Exception e) {
            log.error("导出pdf异常", e);
            e.printStackTrace();
        }
    }

}
